package com.maezia.tdr.controller;

import cn.hutool.http.Header;
import com.maezia.tdr.common.CommonConstant;
import com.maezia.tdr.common.JwtTokenProvider;
import com.maezia.tdr.common.exception.TokenExpiredException;
import com.maezia.tdr.domain.po.ClientDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseController {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    protected ClientDetails getCurrentUser() throws TokenExpiredException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tokenValue = request.getHeader(Header.AUTHORIZATION.getValue());
        String token = tokenValue.substring(CommonConstant.TOKEN_PREFIX_VALUE.length());
        return jwtTokenProvider.getUserInfo(token, ClientDetails.class);
    }
}
